﻿using BasehInfoManager_IDal;
using BasehInfoManagerModel;
using BasehInfoManagerViewModel;
using BasehInfoManagerViewModel.Common;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using zy_11_10.Common.Lib.TypeTools;

namespace BaseInfoManagerDal
{
    public class AdminUserDal : BaseDal, IAdminUserDal
    {
        //注入上下文
        public AdminUserDal(ManagerDbContext managerDbContext) : base(managerDbContext)
        {


        }


        #region 用户显示查询
        //用户显示
        public PagerResult<AdminUser> SearchPage(SearchModel searchModel)
        {
            var query = _managerDbContext.AdminUser.AsQueryable();


            //判断是否有显示查询条件
            if (searchModel.SearchItem != null && searchModel.SearchItem.Count > 0)
            {



                //搜索条件
                var tempDi = searchModel.SearchItem;
                //搜索用户名
                string userName = "user_name";
                //判断搜索条件中是否有用户名
                if (tempDi.Keys.Contains(userName) && !string.IsNullOrEmpty(tempDi[userName]))
                {
                    //模糊差用户名
                    query = query.Where(c => c.user_name.Contains(tempDi[userName]));
                }




                //搜索字用户全名
                string userFullName = "user_full_name";
                //判断搜索条件中是否有用户全名
                if (tempDi.Keys.Contains(userFullName) && !string.IsNullOrEmpty(tempDi[userFullName]))
                {
                    query = query.Where(c => c.user_full_name.Contains(tempDi[userFullName]));
                }

                //状态判断
                string userStatus = "user_status";
                //判断状态
                if (tempDi.Keys.Contains(userStatus) && !string.IsNullOrEmpty(tempDi[userStatus]))
                {
                    int tempStatus = -1;
                    if (int.TryParse(tempDi[userStatus], out tempStatus))
                    {
                        query = query.Where(c => c.user_status == tempStatus);
                    }
                }

                //时间区间查询begin_creator_date  查询开始时间
                string beginCreatorDate = "begin_creator_date";
                //判断时间
                if (tempDi.Keys.Contains(beginCreatorDate) && !string.IsNullOrEmpty(tempDi[beginCreatorDate]))
                {
                    DateTime tempCreatorDate = new DateTime();
                    if (DateTime.TryParse(tempDi[beginCreatorDate], out tempCreatorDate))
                    {
                        query = query.Where(c => c.creator_date >= tempCreatorDate);
                    }
                }


                //时间区间查询begin_creator_date  查询结束时间
                string endCreatorDate = "end_creator_date";
                //判断搜索条件中是否有user_status
                if (tempDi.Keys.Contains(endCreatorDate) && !string.IsNullOrEmpty(tempDi[endCreatorDate]))
                {
                    DateTime tempCreatorDate = new DateTime();
                    if (DateTime.TryParse(tempDi[endCreatorDate], out tempCreatorDate))
                    {
                        query = query.Where(c => c.creator_date <= tempCreatorDate);
                    }
                }


                //根据创建时间排序
                if (!string.IsNullOrEmpty(searchModel.OrderBy))
                {
                    if (searchModel.OrderBy == "creator_date")
                    {
                        if (searchModel.OrderByType == OrderByType.ASC)
                        {
                            query = query.OrderBy(c => c.creator_date);
                        }
                        else
                        {
                            query = query.OrderByDescending(c => c.creator_date);
                        }
                    }


                }



                //排序根据名称
                if (searchModel.OrderBy == "user_full_name")
                {
                    if (searchModel.OrderByType == OrderByType.ASC)
                    {
                        query = query.OrderBy(c => c.user_full_name);
                    }
                    else
                    {
                        query = query.OrderByDescending(c => c.user_full_name);
                    }
                }
            }
            return BasePageSearch(query, searchModel);
        }
        #endregion



        #region 用户添加
        public bool AdminUserAdd(AdminUserView view)
        {
            //创建事物
            using (var tran = _managerDbContext.Database.BeginTransaction())
            {
                try
                {
                    //将实体类转换成模型类
                    AdminUser dbModel = ModelCopier.CreateInstanceFrom<AdminUser>(view);
                    //进行添加
                    _managerDbContext.AdminUser.Add(dbModel);
                    //实例化用户角色关系表
                    List<AdminUserRoleRelation> arrs = new List<AdminUserRoleRelation>();

                    if (view.roleIds != null && view.roleIds.Count > 0)
                    {
                        //循环关系表数据
                        foreach (var roleId in view.roleIds)
                        {
                            arrs.Add(new AdminUserRoleRelation()
                            {
                                user_name = dbModel.user_name,
                                role_id = roleId,
                                creator_date = dbModel.creator_date,
                                creator_name = dbModel.creator_name
                            });


                        }
                        _managerDbContext.AdminUserRoleRelation.AddRange(arrs);

                    }
                    _managerDbContext.SaveChanges();//两个表的数据一起保存
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {

                    tran.Rollback();
                    throw ex;
                }

            }
        }
        #endregion


        #region 查询同用户表
        //查询同用户表
        public AdminUser GetAdminUserByUserName(string userName)
        {
            //如果参数是空返回的是空   否则就返回第一条
            if (string.IsNullOrWhiteSpace(userName)) return null;
            return _managerDbContext.AdminUser.FirstOrDefault(c => c.user_name == userName);
        }
        #endregion



        #region 查找模型表
        public AdminUserView GetAdminUserViewByUserName(string userName)
        {
            if (string.IsNullOrWhiteSpace(userName)) return null;

            var dbUser = GetAdminUserByUserName(userName);
            if (dbUser == null) return null;

            AdminUserView view = ModelCopier.CreateInstanceFrom<AdminUserView>(dbUser);

            view.roles = (from r in _managerDbContext.RoleDb
                          join aur in _managerDbContext.AdminUserRoleRelation on r.role_id equals aur.role_id
                          where aur.user_name == userName
                          select r).ToList();
            if (view.roles != null && view.roles.Count > 0)
                view.roleIds = view.roles.Select(c => c.role_id).ToList();
            return view;
        }
        #endregion



        #region 修改
        public bool AdminUserUpdate(AdminUserView view)
        {
            if (view == null) return false;
            using (var tran=_managerDbContext.Database.BeginTransaction())
            {
                try
                {
                   //查找主键相同的数据
                    AdminUser dbModel = _managerDbContext.AdminUser.FirstOrDefault(a => a.user_name == view.user_name);
                    //这些字段不修改
                    ModelCopier.CopyModel(view, dbModel, "creator_name", "creator_date",
                        "last_lgoin_date", "last_login_ip", "pass_word");
                    //先删除本条数据

                    string sql= "delete admin_user_role_relation where user_name=({0})";
                    //执行删除功能
                    _managerDbContext.Database.ExecuteSqlRaw(sql, view.user_name);
                    List<AdminUserRoleRelation> arrs = new List<AdminUserRoleRelation>();

                    if (view.roleIds != null && view.roleIds.Count > 0)
                    {
                        //循环修改
                        foreach (var roleId in view.roleIds)
                        {
                            arrs.Add(new AdminUserRoleRelation()
                            {
                                user_name = dbModel.user_name,
                                role_id = roleId,
                                creator_date = dbModel.modifi_date.Value,
                                creator_name = dbModel.modifi_name
                            });
                        }
                        //保存两表
                        _managerDbContext.AdminUserRoleRelation.AddRange(arrs);
                    }
                    //保存
                    _managerDbContext.SaveChanges();

                    tran.Commit();
                    return true;

                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }
        }
        #endregion

        #region 修改密码
        public int AdminUserPwdUpdate(string userName,string Npwd)
        {
            var sql = _managerDbContext.AdminUser.Where(a => a.user_name == userName);
            if(sql!=null)
            {
                var q = sql.FirstOrDefault(a => a.user_name == userName);
                q.pass_word = Npwd;
                _managerDbContext.SaveChanges();
                return (1);
            }
            else
            {
                return (0);
            }


        }
        #endregion
    }
}

